﻿using System;
using System.Web;
using System.Text;

using AnOtherBlog.Core;

namespace AnOtherBlog.AJAX
{
	public class Global : System.Web.HttpApplication
	{

		#region Keys for Application and Sessions Collection
		/// <summary>
		/// Estas claves son para manipular los campos en esta clase
		/// Todos los campos se guardan en el Objeto Dictionary Application
		/// </summary>
		const string _ApplicationSessions = "_ApplicationSessions";

		#endregion

		#region Fields and Properties

		/// <summary>
		/// Número de sesiones que se abrieron
		/// </summary>
		public int ApplicationSessions
		{
			get
			{
				if (Application[_ApplicationSessions] == null)
				{
					Application[_ApplicationSessions] = 0;
				}
				return (int) Application[_ApplicationSessions];
			}
			set
			{
				Application[_ApplicationSessions] = value;
			}
		}


		#endregion


		#region Application and Events Handlers
		/// <summary>
		/// Handles the Start event of the Application control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
		protected void Application_Start(object sender, EventArgs e)
		{
			Application.Lock();
			ApplicationSessions = 0;
			Application.UnLock();

			WriteLog("Application Start", true);
		}

		/// <summary>
		/// Handles the Start event of the Session control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
		protected void Session_Start(object sender, EventArgs e)
		{
			Application.Lock();
			ApplicationSessions += 1;

			string domain = this.Request.Url.Host;
			if (!Blog.AnOtherBlogDomains.ContainsKey(domain))
			{
				Blog.AnOtherBlogDomains.Add(domain, Blog.Load(domain));
			}
			Application.UnLock();

			WriteLog(string.Format("Session Start in Host: {0}, Number of Sesions: {1} {2}", domain, ApplicationSessions.ToString(), ListDomains()), true);

			
		}

		protected void Application_BeginRequest(object sender, EventArgs e)
		{
		}

		protected void Application_AuthenticateRequest(object sender, EventArgs e)
		{
		}

		protected void Application_Error(object sender, EventArgs e)
		{
		}

		/// <summary>
		/// Handles the End event of the Session control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
		protected void Session_End(object sender, EventArgs e)
		{
			Application.Lock();
			ApplicationSessions -= 1;
			Application.UnLock();

			WriteLog(string.Format("Session End, Number of Sessions: {0} {1}", ApplicationSessions.ToString(), ListDomains()), true);
		}

		/// <summary>
		/// Handles the End event of the Application control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
		protected void Application_End(object sender, EventArgs e)
		{
			WriteLog("Application End", true);
		}

		#endregion


		#region Helper Methods
		/// <summary>
		/// Escribre una cadena de texto en el archivo de log
		/// </summary>
		/// <param name="strText">Cadena de texto a escribir en el log</param>
		/// <param name="isAppend">Modo de escritura: true=Agrega, false=Sobreescribe</param>
		void WriteLog(string strText, bool isAppend)
		{
			string fileName = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/log.txt");
			System.IO.StreamWriter writer = new System.IO.StreamWriter(fileName, isAppend);
			writer.WriteLine(DateTime.Now.ToString() + ", " + strText);
			writer.Close();
		}

		/// <summary>
		/// Genera una cadena de texto con los dominios activos
		/// </summary>
		/// <returns>Cadena de texto</returns>
		public string ListDomains()
		{
			StringBuilder sb = new StringBuilder();

			sb.AppendLine("\nDominios activos: " + Blog.AnOtherBlogDomains.Count.ToString());
			foreach (string domain in Blog.AnOtherBlogDomains.Keys)
			{
				Blog blog = Blog.AnOtherBlogDomains[domain];
				if (blog != null)
				{
					sb.AppendLine(string.Format("\tDominio: {0} Blog:(id={1}) {2}", domain, blog.BlogID, blog.BlogSettings.Name));
				}
				else
				{
					sb.AppendLine(string.Format("\tDominio: {0} NULL!!!", domain));
				}
			}
			sb.AppendLine("-------------------------------------------------------");
			return sb.ToString();
		}

		#endregion
	}
}